package cn.neusoft.service.impl;

import cn.neusoft.bean.Food;
import cn.neusoft.dao.IFoodDao;
import cn.neusoft.dao.impl.FoodDao;
import cn.neusoft.query.BaseQuery;
import cn.neusoft.query.FoodQuery;
import cn.neusoft.service.IFoodService;
import cn.neusoft.vo.PageBean;
import cn.neusoft.vo.ResultBean;
import com.alibaba.druid.util.StringUtils;

import java.util.List;

public class FoodService implements IFoodService {

    private IFoodDao foodDao;

    public FoodService(){
        foodDao = new FoodDao();
    }

    @Override
    public ResultBean add(Food food) throws Exception {

        if (food==null || StringUtils.isEmpty(food.getFoodName())){
            return ResultBean.ERROR("params null");
        }
        int i = foodDao.add(food);
        return i>0?ResultBean.SUCCESS():ResultBean.ERROR("add food is fail");
    }

    @Override
    public ResultBean update(Food food) throws Exception {
        if (food==null || food.getFoodId()==null || StringUtils.isEmpty(food.getFoodName())){
            return ResultBean.ERROR("params null");
        }
        int i = foodDao.update(food);
        return i>0?ResultBean.SUCCESS():ResultBean.ERROR("update food is fail");
    }

    @Override
    public ResultBean delete(Integer id) throws Exception {
        if (id==null){
            return ResultBean.ERROR("params null");
        }
        int i = foodDao.delete(id);
        return i>0?ResultBean.SUCCESS():ResultBean.ERROR("delete food is fail");
    }

    @Override
    public ResultBean getById(Integer id) throws Exception {
        if (id==null){
            return ResultBean.ERROR("params null");
        }
        Food food = foodDao.getById(id);
        return food==null?ResultBean.ERROR("get food by id is fail"):ResultBean.SUCCESS(food);
    }

    @Override
    public ResultBean getAll() throws Exception {
        List<Food> foods = foodDao.getAll();
        return ResultBean.SUCCESS(foods);
    }

    @Override
    public ResultBean getByPage(BaseQuery baseQuery) throws Exception {

        if (baseQuery==null){
            baseQuery = new FoodQuery();
        }

        PageBean<Food> pageBean = new PageBean<>();

        int count = foodDao.getCount(baseQuery);
        pageBean.setTotalRows(count);

        if(count%baseQuery.getPageCount()==0){
            pageBean.setTotalPages(count/baseQuery.getPageCount());
        }else{
            pageBean.setTotalPages(count/baseQuery.getPageCount()+1);
        }

        List<Food> foodList = foodDao.getByPage(baseQuery);
        pageBean.setData(foodList);

        return ResultBean.SUCCESS(pageBean);
    }

    @Override
    public ResultBean batchDel(List<Integer> ids) throws Exception {
        return null;
    }
}
